<?php
/*
+--------------------------------------------------------------------------
|   Anwsion [#RELEASE_VERSION#]
|   ========================================
|   by Tatfook Network Team
|   (c) 2011 - 2012 Anwsion Software
|   http://www.anwsion.com
|   ========================================
|   Support: zhengqiang@gmail.com
|   
+---------------------------------------------------------------------------
*/

define('IN_AJAX', TRUE);

class c_ajax_class extends AWS_CONTROLLER
{
	function setup()
	{
		HTTP::no_cache_header();
	}
	
	public function send_action()
	{
		if ($this->is_post())
		{
			if ($_GET['tips_id'])
			{
				$tips_id = $_GET['tips_id'];
			}
			else
			{
				$tips_id = 'pm_send';
			}
			
			$sender_uid = $this->user_id;
			$message = htmlspecialchars($_POST["message"]);
			$notice_type = (! isset($_POST["is_system"])) ? 0 : 11;
			$recipient = $_POST["recipient"];
			
			if (trim($message) == '')
			{
				H::ajax_json_output(AWS_APP::RSM(array(
					'tips_id' => $tips_id
				), '-1', "请输入私信内容"));
			}
			
			$rev_info = $this->model('account')->get_users_by_username($recipient);
			
			if (empty($rev_info))
			{
				H::ajax_json_output(AWS_APP::RSM(array(
					'tips_id' => $tips_id
				), '-1', "接收信息的用户不存在"));
			}
			else
			{
				$recipient_uid = $rev_info['uid'];
			}
			
			if ($recipient_uid == $sender_uid)
			{
				H::ajax_json_output(AWS_APP::RSM(array(
					'tips_id' => $tips_id
				), '-1', "接收信息的用户不存在"));
			}
			
			//判断是否设置为关注人发送信息
			if (! $this->model('message')->check_recv($rev_info['uid'], $sender_uid))
			{
				H::ajax_json_output(AWS_APP::RSM(array(
					'tips_id' => $tips_id
				), '-1', "对方设置了只有 Ta 关注的人才能给 Ta 发送私信"));
			}
			
			// !注: 来路检测后面不能再放报错提示
			if (!valid_post_hash($_POST['post_hash']))
			{
				H::ajax_json_output(AWS_APP::RSM(array(
					'tips_id' => $tips_id
				), '-1', '表单来路不正确或内容已提交, 请刷新页面重试'));
			}
			
			if ($this->model('message')->send_message($sender_uid, $recipient_uid, null, $message, 0, 0))
			{
				$this->model('email')->action_email(email_class::TYPE_NEW_MESSAGE, $recipient_uid, get_js_url('/inbox/'), array(
					'user_name' => $this->user_info['user_name'],
				));
				
				if ($_POST['click_id'])
				{
					$rsm = array(
						'click_id' => $_POST['click_id'],
						'tips_id' => $tips_id
					);
				}
				
				H::ajax_json_output(AWS_APP::RSM($rsm, 1, "私信发送成功"));
			}
			else
			{
				H::ajax_json_output(AWS_APP::RSM(array(
					'tips_id' => $tips_id
				), '-1', "私信发送失败, 请联系管理员"));
			}
		}
	}
}